package com.example.rabbit.config;

import cn.hutool.core.util.EnumUtil;
import com.example.rabbit.BeanUtils;
import com.example.rabbit.enums.FanoutEnum;
import org.springframework.amqp.core.AnonymousQueue;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description: 1.fanout交换机 , 这里使用的是AnonymousQueue匿名队列，需要使用的项目调用FanoutConfig.init()初始化匿名队列。
 * 2.消费者指定队列名称， 队列名称是  "#{交换机名称_queue.name}"
 * 3. @RabbitListener(queues = "#{k_line_queue.name}").
 */
@Configuration
@DependsOn({"beanUtils"})
public class FanoutConfig {


    private final static String xMessageTt = "x-message-ttl";

    private static LinkedHashMap<String, FanoutEnum> fanoutMap;

    static {
        fanoutMap = EnumUtil.getEnumMap(FanoutEnum.class);
    }


    @PostConstruct
    public void fanoutExchange() {
        FanoutExchange fanoutExchange;
        for (Map.Entry<String, FanoutEnum> entry : fanoutMap.entrySet()) {
            fanoutExchange = new FanoutExchange(entry.getValue().getExchange());
            BeanUtils.registerBean(entry.getValue().getExchange(), fanoutExchange);
        }
    }

    /**
     * 初始化匿名队列对象及绑定交换机
     */
    public static void init() {
        FanoutExchange fanoutExchange;
        Queue queue;
        for (Map.Entry<String, FanoutEnum> entry : fanoutMap.entrySet()) {
            fanoutExchange = BeanUtils.getBean(entry.getValue().getExchange(), FanoutExchange.class);
            queue = new AnonymousQueue();
            if (entry.getValue().getTtl() != null) {
                queue.addArgument(xMessageTt, entry.getValue().getTtl());
            }
            BeanUtils.registerBean(entry.getValue().objName(), queue);
            BeanUtils.registerBean(entry.getKey(), BindingBuilder.bind(queue).to(fanoutExchange));
        }
    }
}
